#include "SoundManager.h"

#include <stdexcept>

SoundManager * SoundManager::manager = 0;


namespace
{
	irrklang::vec3df OgreVectAIrr(Ogre::Vector3 const & vec) 
	{ 
		return irrklang::vec3df(vec.x, vec.y, vec.z);
	}
}

void SoundManager::UpdateListener(Ogre::Vector3 const & pos, Ogre::Vector3 const & dirVista,
		Ogre::Vector3 const & velocidad, 
		Ogre::Vector3 const & vectArriba)
{
	engine->setListenerPosition(OgreVectAIrr(pos), OgreVectAIrr(dirVista), OgreVectAIrr(velocidad),
		OgreVectAIrr(vectArriba));
}

SoundManager::SoundManager(void)
{
	engine = createIrrKlangDevice();
	if (!engine)
	{
		std::cout << "Excepcion: Inicializacion de motor de audio erronea" << std::endl;
		throw std::runtime_error("Al inicializar irrklang::engine");
	}
	if (manager == 0)
	{
		manager = this;
	}
	else 
		throw std::runtime_error("SoundManager es un singleton y no puede ser instanciado de nuevo.");
	
	engine->setDefault3DSoundMinDistance(300);
	engine->setRolloffFactor(0.00001);
}

SoundManager::~SoundManager(void)
{
	engine->drop();
}

void SoundManager::AnadirSonido(std::string ident, const char * archivo, float vol)

{
	irrklang::ISoundSource * p = engine->addSoundSourceFromFile(archivo);
	mp[ident] = p;
	p->setDefaultVolume(vol);
}

//A implementar radio de sonoridad de cada Object

void SoundManager::ReproducirFX(std::string ident, Ogre::Vector3 const & pos)
{
	irrklang::vec3df ipos(pos.x, pos.y, pos.z);
	/*mp[ident]->setDefaultVolume()*/
	engine->play3D(mp[ident], ipos); 
}

SoundManager * SoundManager::GetSingleton()
{
	return (manager);
}

void SoundManager::FinalizarMusic(std::string ident)
{
	engine->stopAllSounds();

}

void SoundManager::ReproducirMusic(std::string ident)
{
	engine->play2D(mp[ident], true);
}

void SoundManager::SwitchMusic(std::string ident1, std::string ident2)
{
	engine->stopAllSounds();
	engine->play2D(mp[ident2], true);
}

void SoundManager::AlternateFX(std::string ident1, std::string ident2, Ogre::Vector3 const & pos)

{
	static bool swi;

	irrklang::vec3df ipos(pos.x, pos.y, pos.z);

	if (swi)
	{
		swi = false;
		engine->play3D(mp[ident1], ipos);
	}
	else
	{
		swi = true;
		engine->play3D(mp[ident2], ipos);
	}
}


	

